package com.hskn.hss.utils;

import java.util.List;

public class GeometryUtil {

    /**
     * 获取点与直线之间的距离
     *
     * @param p 点
     * @param a 直线上一点
     * @param b 直线上一点
     * @return
     */
    public static double pointToLineDist(Point p, Point a, Point b) {
        double ABx = b.x - a.x;
        double ABy = b.y - a.y;
        double APx = p.x - a.x;
        double APy = p.y - a.y;

        double AB_AP = ABx * APx + ABy * APy;
        double distAB2 = ABx * ABx + ABy * ABy;

        double Dx = a.x, Dy = a.y;
        if (distAB2 != 0) {
            double t = AB_AP / distAB2;
            if (t >= 1) {
                Dx = b.x;
                Dy = b.y;
            } else if (t > 0) {
                Dx = a.x + ABx * t;
                Dy = a.y + ABy * t;
            } else {
                Dx = a.x;
                Dy = a.y;
            }
        }
        double PDx = Dx - p.x, PDy = Dy - p.y;
        return Math.sqrt(PDx * PDx + PDy * PDy);
    }

    /**
     * 获取点与多边形之间最近距离
     *
     * @param point
     * @param points
     * @return 0.0 ：点位于多边形内部 >0.0 : 点与多边形之间的最近距离
     */
    public static double pintoToPolygonMinDist(Point point, List<Point> points) {
        double dist = Double.MAX_VALUE;
        int N = points.size();
        for (int i = 0, j = N - 1; i < N; j = i++) {
            dist = Math.min(dist, pointToLineDist(point, points.get(i), points.get(j)));
        }
        return dist;
    }
}

